package com.jinxinol.core.util.encryption;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Utils {
	/**
	 * 缺省字符编码
	 */
	private static String DEFAULT_ENCODING = "UTF-8";
	
	private static BASE64Encoder base64encoder = new BASE64Encoder();
	
	private static BASE64Decoder base64decoder = new BASE64Decoder();
	
	public static String encodeBase64(byte[] bytes) {
		return base64encoder.encode(bytes);
	}
	
	public static String encodeBase64(String src, String encoding)throws Exception{
		try {
			return encodeBase64(src.getBytes(encoding));
		} catch (UnsupportedEncodingException e) {
			throw new Exception("BASE64编码过程发生异常");
		}
	}
	
	public static String encodeBase64(String src)throws Exception{
		return encodeBase64(src.getBytes(DEFAULT_ENCODING));
	}
	
	public static String decodeBase64(String codedStr, String encoding) throws Exception{
		try {
			byte[] bytes = base64decoder.decodeBuffer(codedStr);
			return new String(bytes, encoding);
		} catch (IOException e) {
			throw new Exception("BASE64解码过程发生异常");
		}
	}
	
	public static String decodeBase64(String codedStr) throws Exception{
		return decodeBase64(codedStr, DEFAULT_ENCODING);
	}
	
	public static void main(String[] args) throws Exception {
		
		String info = "我";
		for(int i=0; i<100; i++){
			if(i!= 1){
				info += "我";
			}
			
			System.out.println("加密前的明文：" + info);
			System.out.println("加密前的明文 length：" + info.length());
			
			String ciphertext = Base64Utils.encodeBase64(info);
			System.out.println("加密后的密文：" + ciphertext);
			System.out.println("加密后的密文 length：" + ciphertext.length());
			System.out.println("=======================================");
		}
	}
}
